package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.Banco;
import ar.republicagroup.gestion.entities.Cheque;
import ar.republicagroup.gestion.entities.ChequeTipo;
import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.services.BancoServices;
import ar.republicagroup.gestion.services.ChequeServices;
import ar.republicagroup.gestion.services.ChequeTipoServices;
import ar.republicagroup.gestion.services.ClienteServices;
import ar.republicagroup.gestion.services.CodigoPostalServices;
import ar.republicagroup.gestion.util.ClickAction;
import ar.republicagroup.gestion.util.JComboBoxModel;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.UserSession;
import ar.republicagroup.gestion.util.Validar;
import ar.republicagroup.gestion.util.messages.UIMessages;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class modalPanelEditCheque extends javax.swing.JDialog {

    ClienteServices clienteServices             = (ClienteServices)SpringUtils.getBean("clienteServices");
    ChequeTipoServices chequeTipoServices       = (ChequeTipoServices)SpringUtils.getBean("chequeTipoServices");
    ChequeServices     chequeServices           = (ChequeServices)SpringUtils.getBean("chequeServices"); 
    BancoServices      bancoServices            = (BancoServices)SpringUtils.getBean("bancoServices"); 
    CodigoPostalServices codigoPostalServices   = (CodigoPostalServices)SpringUtils.getBean("codigoPostalServices");
    
    /* Beans */
    private Cheque chequeToUpdate ;
    private Cliente cliente;
    private Banco banco;
    
    /* PARAMS QUE RECIBE PARA SETEAR LOS DATOS EN EL FORMULARIO */
    private int clienteId;
    
    /*CONSTANTES*/
    private static final boolean CHEQUE_INVALIDO = false;
    private static final boolean CHEQUE_VALIDO   = true;
    
    /* Flag para indicar si el cheque lo está editando al momento de registrar una bolsa  */
    private boolean editandoEnBolsa     = false;
    /* Flag para indicar si un cheque es valido luego de haber pasado la validación */
    boolean cheque_valido       = false;
    /* Flag para indicar si ha concluido con el edit del cheque correctamente */
    private boolean editCompleted;
    
    
    private static Logger log = Logger.getLogger(modalPanelEditCheque.class);
    
    
    
    
    public modalPanelEditCheque(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        cargarCombos();
    }
     
    private void valoresPorDefecto(){
        lblErrorImporte.setVisible(false);    
    }
    
    private void mostrarDatosDeCheque(){
        /* SELECCIONAMOS EL ITEM QUE CORRESPONDE EN LOS COMBOS*/
        DefaultComboBoxModel modelClienteCombo = (DefaultComboBoxModel) comboCliente.getModel();
        if(isEditandoEnBolsa()){
            seleccionarItemEnCombo(modelClienteCombo, getClienteId(),comboCliente);
            txtCodigoString.setEditable(false);
            comboCliente.setEnabled(false);
            comboChequeTipo.requestFocus();
        }else {
            seleccionarItemEnCombo(modelClienteCombo, getChequeToUpdate().getBolsaChequeId().getClienteId().getId(),comboCliente);
        }
        
        DefaultComboBoxModel modelChequeTipo = (DefaultComboBoxModel) comboChequeTipo.getModel();
        seleccionarItemEnCombo(modelChequeTipo, getChequeToUpdate().getChequeTipoId().getId(), comboChequeTipo);
        
        txtCodigoString.setText(getChequeToUpdate().getCodigoString());
        txtBanco.setText(getChequeToUpdate().getBancoId().getNombre());
        txtNroCheque.setText(getChequeToUpdate().getChequeNro());
        txtNroCuenta.setText(getChequeToUpdate().getCodigoCtaBancaria());
        txtOrigen.setText(getChequeToUpdate().getOrigen());
        txtComision.setText(getChequeToUpdate().getComision().toString());
        txtImporte.setText(getChequeToUpdate().getImporte().toString());
    }
    
    private void cargarCombos(){
        comboCliente.setModel(clienteServices.combo());
        comboChequeTipo.setModel(chequeTipoServices.combo());
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelContenedor = new javax.swing.JPanel();
        comboCliente = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtCodigoString = new javax.swing.JTextField();
        comboChequeTipo = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        txtBanco = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtNroCheque = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtNroCuenta = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        txtOrigen = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        txtComision = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        txtImporte = new javax.swing.JTextField();
        btnModificar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        lblErrorImporte = new javax.swing.JLabel();
        lblChequeCorrecto = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Modificar cheque :...");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        panelContenedor.setBorder(javax.swing.BorderFactory.createTitledBorder("Modificar cheque"));

        comboCliente.setBackground(new java.awt.Color(204, 204, 255));
        comboCliente.setEnabled(false);
        comboCliente.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboClienteItemStateChanged(evt);
            }
        });

        jLabel1.setText("Cliente");

        jLabel2.setText("Ingrese código");

        txtCodigoString.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoStringKeyPressed(evt);
            }
        });

        comboChequeTipo.setNextFocusableComponent(txtImporte);
        comboChequeTipo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                comboChequeTipoKeyPressed(evt);
            }
        });

        jLabel3.setText("Tipo cheque");

        txtBanco.setEditable(false);
        txtBanco.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N

        jLabel5.setText("Banco");

        txtNroCheque.setEditable(false);

        jLabel6.setText("Nro.Cheque");

        txtNroCuenta.setEditable(false);

        jLabel7.setText("Nro.Cuenta");

        jLabel8.setText("Origen");

        txtOrigen.setEditable(false);

        jLabel9.setText("Comisión");

        txtComision.setEditable(false);

        jLabel10.setText("Importe");

        txtImporte.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtImporteFocusLost(evt);
            }
        });
        txtImporte.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtImporteKeyPressed(evt);
            }
        });

        InputMap inputMap = btnModificar.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW);
        KeyStroke ctrl_r = KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK);
        inputMap.put(ctrl_r, "CTRL_R");
        btnModificar.getActionMap().put("CTRL_R", new ClickAction(btnModificar));
        btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/edit.png"))); // NOI18N
        btnModificar.setText("Modificar");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        lblErrorImporte.setForeground(new java.awt.Color(255, 0, 0));
        lblErrorImporte.setText("Mensaje de error");

        lblChequeCorrecto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/check.png"))); // NOI18N

        javax.swing.GroupLayout panelContenedorLayout = new javax.swing.GroupLayout(panelContenedor);
        panelContenedor.setLayout(panelContenedorLayout);
        panelContenedorLayout.setHorizontalGroup(
            panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelContenedorLayout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel10)
                    .addComponent(jLabel9)
                    .addComponent(jLabel8)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelContenedorLayout.createSequentialGroup()
                        .addComponent(comboChequeTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(panelContenedorLayout.createSequentialGroup()
                        .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panelContenedorLayout.createSequentialGroup()
                                .addComponent(btnModificar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnCancelar))
                            .addGroup(panelContenedorLayout.createSequentialGroup()
                                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(txtNroCuenta)
                                        .addComponent(txtNroCheque)
                                        .addComponent(comboCliente, 0, 255, Short.MAX_VALUE)
                                        .addComponent(txtOrigen)
                                        .addComponent(txtCodigoString))
                                    .addComponent(txtComision, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtBanco, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(panelContenedorLayout.createSequentialGroup()
                                        .addComponent(txtImporte, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(lblErrorImporte)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(lblChequeCorrecto)))
                        .addGap(0, 21, Short.MAX_VALUE))))
        );
        panelContenedorLayout.setVerticalGroup(
            panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelContenedorLayout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCodigoString, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(lblChequeCorrecto))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboChequeTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtBanco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNroCheque, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNroCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtOrigen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtComision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtImporte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10)
                    .addComponent(lblErrorImporte))
                .addGap(18, 18, 18)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnModificar)
                    .addComponent(btnCancelar))
                .addContainerGap(42, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelContenedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelContenedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    public Cheque getChequeToUpdate() {
        return chequeToUpdate;
    }

    public void setChequeToUpdate(Cheque chequeToUpdate) {
        this.chequeToUpdate = chequeToUpdate;
    }

    public int getClienteId() {
        return clienteId;
    }

    public void setClienteId(int clienteId) {
        this.clienteId = clienteId;
    }

    public boolean isEditandoEnBolsa() {
        return editandoEnBolsa;
    }

    public void setEditandoEnBolsa(boolean editandoEnBolsa) {
        this.editandoEnBolsa = editandoEnBolsa;
    }
    
    private void comboClienteItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboClienteItemStateChanged
        JComboBoxModel model     = (JComboBoxModel) comboCliente.getSelectedItem();
        int id_cliente           = Integer.valueOf(model.getValue());

        if (id_cliente !=0){
            cliente = clienteServices.get(id_cliente);
        } else {
            txtCodigoString.setEditable(false); 
        }
    }//GEN-LAST:event_comboClienteItemStateChanged

    private void txtCodigoStringKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoStringKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            String codigoDeCheque = txtCodigoString.getText();
            if(codigoDeCheque.length() > 0){
                txtCodigoString.setText(chequeServices.limpiarCodigoDeCheque(codigoDeCheque));
                if(txtCodigoString.getText().length() == ChequeServices.TAMANO_CODIGO_CHEQUE){
                    if(!(txtCodigoString.getText().equals(getChequeToUpdate().getCodigoString()))){
                        cheque_valido = true;
                    if(!chequeServices.isChequeRegistered(txtCodigoString.getText())){
                            validarDatosDeCheque(txtCodigoString.getText());
                    }else{
                        JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("duplicatedCheque"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
                        txtCodigoString.requestFocus();
                        txtCodigoString.selectAll();
                        mostrarLabelDeChequeValido(CHEQUE_INVALIDO);
                        //limpiarFormulario();
                    }
                    }
                } else {
                    JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("invalidCheque"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
                    //limpiarFormulario();
                    txtCodigoString.requestFocus();
                    txtCodigoString.selectAll();
                    mostrarLabelDeChequeValido(CHEQUE_INVALIDO);
                }
            } else {
                JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredInputCheque"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
                txtCodigoString.requestFocus();
            }
        }
    }//GEN-LAST:event_txtCodigoStringKeyPressed

    public void mostrarLabelDeChequeValido(boolean esValido){
        if(esValido){
          lblChequeCorrecto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/check.png")));
        }else{
          lblChequeCorrecto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cancel.png")));
        }
        
         lblChequeCorrecto.setVisible(true);
    }
    
    /* Pasar a lógica de negocio de ChequeServices */
    public void validarDatosDeCheque(String codigo_cheque_ingresado){
                String cod_cuenta_banco		= null;
		String cod_cuenta_sucursal	= null;
		String cod_postal 		= null;
		String nro_cheque               = null;
		String cuenta_bancaria		= null;
		String codigo_de_cheque 	= codigo_cheque_ingresado;
                
                    
                /* DESCOMPONEMOS LA CADENA Y OBTENEMOS LOS CODIGOS RESPECTIVOS */
                cod_cuenta_banco                    = codigo_de_cheque.substring(0, 3);
                cod_cuenta_sucursal                 = codigo_de_cheque.substring(3, 6);
		cod_postal                          = codigo_de_cheque.substring(6,10);
                nro_cheque                          = codigo_de_cheque.substring(10, 18);
		cuenta_bancaria                     = codigo_de_cheque.substring(18);
                banco                               = bancoServices.findBancoByCodCuenta("00"+cod_cuenta_banco, false);
                        
                            if(banco != null){
                                txtBanco.setText(banco.getNombre());
                                String origen                       = codigoPostalServices.getOrigenOfCodigoPostalByCodigo(Integer.valueOf(cod_postal));
                                txtOrigen.setText(origen);
                                txtNroCheque.setText(nro_cheque);
                                txtNroCuenta.setText(cuenta_bancaria);
                        
                                    if(origen.equals(ChequeServices.ORIGEN_CAP_BSAS)){
                                        txtComision.setText(cliente.getComisionBa().toString());
                                    }else{
                                        txtComision.setText(cliente.getComisionInterior().toString());
                                    }
                                   
                                    cheque_valido = true;
                                    comboChequeTipo.requestFocus();
                                    mostrarLabelDeChequeValido(CHEQUE_VALIDO);
                            } else {
                                JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("invalidBanco"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
                                txtCodigoString.requestFocus();
                                txtCodigoString.select(0, 3);
                            }
    }
    
    public boolean esValidoElFormulario(){
        
        if(!cheque_valido){
            validarDatosDeCheque(txtCodigoString.getText());
        }
        
        if(!cheque_valido){
            mostrarMensajeJOptionPane(UIMessages.getErrorMessage("invalidCheque"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
            txtCodigoString.requestFocus();
            txtCodigoString.selectAll();
            return false;
        }
        
        return true;
    }
    
    
     public void mostrarMensajeJOptionPane(String mensaje,String titulo_ventana,int tipo_de_mensaje){
        JOptionPane.showMessageDialog(this, mensaje, titulo_ventana, tipo_de_mensaje);
    }
    
    
    
    
    private void comboChequeTipoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_comboChequeTipoKeyPressed
//        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
//            txtImporte.getText();
//        }
    }//GEN-LAST:event_comboChequeTipoKeyPressed

    private void txtImporteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtImporteFocusLost
       // esValidoElImporte();
    }//GEN-LAST:event_txtImporteFocusLost

    private void txtImporteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtImporteKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            if(esValidoElImporte()){
              btnModificar.doClick();
            }
        }
    }//GEN-LAST:event_txtImporteKeyPressed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed

        /*Obtenemos los id de los combos*/
            JComboBoxModel model_tipocheque     = (JComboBoxModel)comboChequeTipo.getSelectedItem(); 
        
            log.info("Editando cheque como administrador ("+UserSession.getInstance().getUser_name()+") "+"->"+getChequeToUpdate().getId());
            
            /*Cargamos los datos en el Bean de Cheque*/
            if(esValidoElFormulario()){
                Cheque cheque = new Cheque();
                cheque.setId(getChequeToUpdate().getId());
                cheque.setBolsaChequeId(getChequeToUpdate().getBolsaChequeId());
		cheque.setChequeNro(txtNroCheque.getText());
		cheque.setCodigoString(txtCodigoString.getText());
		cheque.setFechaAlta(getChequeToUpdate().getFechaAlta());
		cheque.setCodigoCtaBancaria(txtNroCuenta.getText());
		cheque.setImporte(BigDecimal.valueOf(Double.parseDouble(txtImporte.getText())));
                cheque.setBancoId(banco);
                cheque.setChequeTipoId(new ChequeTipo(Integer.valueOf(model_tipocheque.getValue())));
                cheque.setComision(BigDecimal.valueOf(Double.parseDouble(txtComision.getText())));
                cheque.setOrigen(txtOrigen.getText());
                cheque.setCuentaBancoId(getChequeToUpdate().getCuentaBancoId());
                cheque.setChequeEstadoId(getChequeToUpdate().getChequeEstadoId());
                cheque.setFechaLiquidado(getChequeToUpdate().getFechaLiquidado());
                cheque.setFechaPendiente(getChequeToUpdate().getFechaPendiente());
                cheque.setGestionEnRechazos(getChequeToUpdate().getGestionEnRechazos());
                cheque.setFechaUpdate(new Date());
    		cheque.setEstado(getChequeToUpdate().getEstado());
                cheque.setGestionEnRechazos(getChequeToUpdate().getGestionEnRechazos());
               
                String mensaje;
                
                if(isEditandoEnBolsa()){
                     frmAddCheque.setChequeEditado(cheque);
                     frmAddCheque.actualizarListadoConChequeEditado();
                     mensaje = UIMessages.getInfoMessage("onCompleteUpdate");
                }else {
                     mensaje = chequeServices.update(cheque);
                }
                
                if(mensaje != null){
                   JOptionPane.showMessageDialog(this, mensaje, UIMessages.getInfoMessage("onCompleteUpdate_title"), JOptionPane.INFORMATION_MESSAGE);
                   editCompleted = true;
                   dispose();
                } else {
                     JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onInsertError"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
                }
            
           
                
            }
    }//GEN-LAST:event_btnModificarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
      mostrarDatosDeCheque(); 
      valoresPorDefecto();  
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
       if(!isEditandoEnBolsa()){
            frmCheque.btnActualizar.doClick();
       }   
    }//GEN-LAST:event_formWindowClosed

    private void seleccionarItemEnCombo(DefaultComboBoxModel model,int id,JComboBox combo){
        int indice = 0;
        for (int i = 0; i < model.getSize() ; i++) {
          JComboBoxModel item =  (JComboBoxModel)model.getElementAt(i);
            if(id == Integer.valueOf(item.getValue())){
                    indice = i;
                    }
            }       
           model.setSelectedItem(model.getElementAt(indice)); 
           combo.setModel(model);
    }
    
    public boolean esValidoElImporte(){
        txtImporte.setText(Validar.cambiarComaPorPuntoEnCadena(txtImporte.getText())); 
        if(!Validar.esVacio(txtImporte.getText())&& !Validar.validarVacio(txtImporte.getText())){
           if(Validar.esUnDatoDouble(txtImporte.getText())){
               lblErrorImporte.setVisible(false);
               return true;
           }else{
               
               JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("decimal"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
               return false;
           }
       }else{
           JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("decimal"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
           return false;
       }
    
    }
    
    
   
    public boolean isEditCompleted() {
        return editCompleted;
    }

    
    public void setIsEditCompleted(boolean editCompleted) {
        this.editCompleted = editCompleted;
    }
    
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
       java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                modalPanelEditCheque dialog = new modalPanelEditCheque(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JComboBox comboChequeTipo;
    private javax.swing.JComboBox comboCliente;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel lblChequeCorrecto;
    private javax.swing.JLabel lblErrorImporte;
    private javax.swing.JPanel panelContenedor;
    private javax.swing.JTextField txtBanco;
    private javax.swing.JTextField txtCodigoString;
    private javax.swing.JTextField txtComision;
    private javax.swing.JTextField txtImporte;
    private javax.swing.JTextField txtNroCheque;
    private javax.swing.JTextField txtNroCuenta;
    private javax.swing.JTextField txtOrigen;
    // End of variables declaration//GEN-END:variables

    
}
